package com.proxyhub.crawler;

import com.proxyhub.annotation.Crawler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by linxsh on 2017/6/28.
 */
@Service
public class CrawlerStarter {

    private static final Logger logger = LoggerFactory.getLogger(CrawlerStarter.class);

    private final URL packagePath = this.getClass().getResource("");

    private final String packageName = this.getClass().getPackage().getName();

    private final ExecutorService exec = Executors.newFixedThreadPool(10);

    public void start(HttpServletRequest request) {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        if(wac != null) {
            String[] crawlersBeanNames = wac.getBeanNamesForAnnotation(Crawler.class);
            for(String crawlerBeanName : crawlersBeanNames) {
                BaseCrawler crawler = wac.getBean(crawlerBeanName, BaseCrawler.class);
                exec.execute(crawler);
            }
        }
    }

    /*public void crawl() {
        try {
            File crawlerPackage = ResourceUtils.getFile(packagePath.toURI());
            if(crawlerPackage.exists() && crawlerPackage.isDirectory()) {
                for(File crawlerJavaFile: crawlerPackage.listFiles()) {
                    String simpleFileName = StringUtils.substringBeforeLast(crawlerJavaFile.getName(), ".");
                    Class<?> clazz = Class.forName(packageName + "." + simpleFileName);
                    Crawler crawler = clazz.getAnnotation(Crawler.class);
                    if(crawler == null) {
                        continue;
                    }
                    try {
                        BaseCrawler baseCrawler = (BaseCrawler) clazz.newInstance();
                        new Thread(baseCrawler).start();
                        logger.info(crawler.value() + "\t started...");
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }*/
}
